# coding:utf8
''''
    代理经销商相关
'''
from flask_restful import Resource, request
from _sys.parser import parsers
from _sys.models import MongodbOperations, ResponseJson, Token, CreateId, FormatIO
from _sys.code import dbNameDict
from _sys.function import allow_cross, admin_open_ips, had_power,format_words, parse_param_info
from _app.web import Dicts

import time

mgOp = MongodbOperations()
responseJson = ResponseJson()
token = Token()
cId = CreateId()

class Agent(Resource):
    '''
        /agt
        get -- 获取经销商信息 list or detail
        post -- 修改经销商信息
        put -- 新增经销商信息
        delete -- 删除经销商信息
    '''
    @allow_cross
    def get(self):
        args = parsers()
        admin_dict = Dicts().admin()
        a_ip = request.remote_addr
        agt_code = args.get('code')
        start_t = args.get('start_t')
        end_t = args.get('end_t')
        if agt_code:   # 获取单个经销商信息
            rd = mgOp.find_one(dbNameDict['agentData'], filter={'agt_code': agt_code})
            if rd:
                rd['create_admin'] = admin_dict[rd['create_admin']]
                return responseJson.correct(code='ok', data={'data':[rd], 'ip': a_ip})   # 成功
            else:
                return responseJson.error_response(code='unknownError')  # 失败
        else:    # 获取列表
            filter = {}
            if start_t:
                filter['create_time'] =  {"$gte": str(time.mktime(time.strptime(start_t,"%Y-%m-%d-%H:%M:%S")))}
            if end_t:
                filter['create_time'] = {"$lte": str(time.mktime(time.strptime(end_t, "%Y-%m-%d-%H:%M:%S")))}
            rds = mgOp.find_many(dbNameDict['agentData'], filter=filter)
            for rd in rds:
                rd['create_admin'] = admin_dict[rd['create_admin']]
            if rds:
                return responseJson.correct(code='ok', data={'data':rds, 'ip': a_ip})
            else:
                return responseJson.error_response(code='resourcesDoNotExist')

    @allow_cross
    def post(self):
        '''
            修改信息
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        agt_code = args.get('code')
        agt_name = args.get('name')    # 店名   cn:xxxxxx|en:xxxxxx|tw:xxxxxxx
        agt_intro = args.get('intro')   # 介绍
        agt_addr = args.get('addr')    # 地址
        agt_phone = args.get('phone')  # 联系电话
        agt_coordinates = args.get('coordinates')  # 坐标 由前端将地址转化
        agt_open_daily = args.get('time') # 营业时间
        agt_status = args.get('status')  # 经销商状态
        agt_fax = args.get('fax')
        agt_merge = args.get('merge') # 归并区域
        agt_img = args.get('img')

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanModifyAgent', powers):   # 不具有权限
            return responseJson.error_response(code='permissionsValidationFailure')

        new_data = {}

        if agt_name:
            new_data['agt_name'] = format_words(parse_param_info(agt_name))
        if agt_intro:
            new_data['agt_intro'] = format_words(parse_param_info(agt_intro))
        if agt_addr:
            new_data['agt_addr'] = format_words(parse_param_info(agt_addr))
            new_data['agt_coordinates'] = parse_param_info(agt_coordinates)
        if agt_phone:
            new_data['agt_phone'] = agt_phone
        if agt_open_daily:
            new_data['agt_open_daily'] = agt_open_daily
        if agt_status:
            new_data['agt_status'] = agt_status
        if agt_merge:
            new_data['agt_merge'] = format_words(parse_param_info(agt_merge))
        if agt_fax:
            new_data['agt_fax'] = agt_fax
        if agt_img:
            new_data['agt_img'] = agt_img
        if new_data:
            if mgOp.update_one(dbNameDict['agentData'], filter={'agt_code':agt_code}, data=new_data):
                return responseJson.correct(code='ok', data={'msg':'修改经销商信息成功'})
            else:
                return responseJson.error_response(code='unknownError')
        else:
            return responseJson.error_response(code='lackOfNecessaryParameters')

    @allow_cross
    def put(self):
        '''
            新增经销商信息
        :return:
        '''
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        agt_name = args.get('name')  # 店名
        agt_intro = args.get('intro')  # 介绍
        agt_addr = args.get('addr')  # 地址
        agt_phone = args.get('phone')  # 联系电话
        agt_coordinates = args.get('coordinates')  # 坐标 由前端将地址转化
        agt_open_daily = args.get('time')  # 营业时间
        agt_code = args.get('code')
        agt_fax = args.get('fax')
        agt_merge = args.get('merge')  # 归并区域
        agt_img = args.get('img')

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanAddAgent', powers):   # 不具有权限
            return responseJson.error_response(code='permissionsValidationFailure')

        if mgOp.find_one(dbNameDict['agentData'], filter={'agt_code': agt_code}):
            return responseJson.error_response(code='resourcesHadExist')

        if agt_name and agt_intro and agt_phone and agt_coordinates and agt_open_daily:
            w_agt = cId.agtid(format_words(parse_param_info(agt_name))['cn'], format_words(parse_param_info(agt_addr))['cn'])
            agt_data = {
                'w_agt':w_agt,
                'agt_name':format_words(parse_param_info(agt_name)),
                'agt_intro':format_words(parse_param_info(agt_intro)),
                'agt_addr':format_words(parse_param_info(agt_addr)),
                'agt_phone':agt_phone,
                'agt_coordinates':parse_param_info(agt_coordinates),
                'agt_open_daily':agt_open_daily,
                'create_time':str(time.time()),
                'format_time': FormatIO().timestamp_format(time.time()),
                'create_admin':a_id,
                'agt_code':agt_code,
                'agt_fax':agt_fax,
                'agt_merge':format_words(parse_param_info(agt_merge)),
                'agt_img':agt_img,
                'agt_status':'1'
            }
            if mgOp.insert_one(dbNameDict['agentData'], agt_data):
                return responseJson.correct(code='ok', data={'msg':'新增经销商成功'})
            else:
                return responseJson.error_response(code='unknownError')
        else:
            return responseJson.error_response(code='lackOfNecessaryParameters')

    @allow_cross
    def delete(self):
        args = parsers()
        a_id = args.get('a_id')
        a_token = args.get('a_token')
        a_ip = request.remote_addr
        agt_code = args.get('code')

        if not admin_open_ips(a_ip):     # ip 非法
            return responseJson.error_response(code='understandRequestButRefused')

        if not token.verify(token=a_token, _id=a_id):   # token 失效
            return responseJson.error_response(code='tokenFailure')

        a_role_id = mgOp.find_one(dbNameDict['adminData'], filter={'a_id': a_id})['a_role_id']
        powers = mgOp.find_one(dbNameDict['adminRoleData'], filter={'role_id': a_role_id})['powers']

        if not had_power('CanDeleteAgent', powers):   # 不具有权限
            return responseJson.error_response(code='permissionsValidationFailure')

        if mgOp.delete_one(dbNameDict['agentData'], filter={'agt_code':agt_code}):
            return responseJson.correct(code='ok', data={'msg':'删除经销商信息成功'})




























